#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
import time
import re
import datetime
import calendar
import pa

def get_base_dir(obj):
    directory = obj['directory']
    t = int(time.time())
    t_list = time.localtime(t)
    t = time.strftime('%Y-%m-%d', t_list)
    t = t + " 00:00:00"
    t = time.strptime(t, "%Y-%m-%d %H:%M:%S")
    t = int(time.mktime(t))
    t_list = time.localtime(t)
    dir_name = time.strftime('%Y-%m-%d', t_list)
    now_dir = os.getcwd()
    os.chdir(directory)
    now_dir2 = os.getcwd()
    os.chdir(now_dir)
    base_dir = now_dir2 + '/' + dir_name
    return base_dir


def day_OK():
    return True

def week_OK():
    d=datetime.datetime.now()
    if d.weekday() == 0:
        return True
    else:
        return False

def month_OK():
    t = time.time()
    t_list = time.localtime(t)
    d = int(time.strftime('%d', t_list))
    if d == 1:
        return True
    else:
        return False

def get_last_month_days():
    t = time.time()
    t_list = time.localtime(t)
    y = int(time.strftime('%Y', t_list))
    m = int(time.strftime('%m', t_list))
    if m > 1:
        m = m - 1
    elif m == 1:
        m = 12
        y = y - 1
    rtn = calendar.monthrange(y, m)
    return rtn[1]


def run_main():
    if len(sys.argv) != 2:
        print('参数错误，如：./daemon_pa.py /var/CactiEZ_Pa')
        sys.exit(-1)
    #获取到dir的绝对路径
    directory = sys.argv[1]
    if not os.path.exists(directory):
        os.makedirs(directory)
    os.chdir(directory)
    directory = os.getcwd()    
    while 1:
        base_dir = get_base_dir({'directory':directory})

        t = time.time()
        t_list = time.localtime(t)
        end_time = time.strftime('%Y-%m-%d', t_list)
        #~~~~~~~~~~~main~start~~~~~~~~ 
        if day_OK():
            dir_day = base_dir + '_day'
            if not os.path.exists(dir_day):
                pa.run_pa({'end_time':end_time, 'offset':'1', 'directory':dir_day})
                os.system('zip -r ' + dir_day + '.zip ' + dir_day)
        if week_OK():
            dir_week = base_dir + '_week'
            if not os.path.exists(dir_week):
                pa.run_pa({'end_time':end_time, 'offset':'7', 'directory':dir_week})
                os.system('zip -r ' + dir_week + '.zip ' + dir_week)
        if month_OK():
            dir_month = base_dir + '_month'
            day = str(get_last_month_days())
            if not os.path.exists(dir_month):
                pa.run_pa({'end_time':end_time, 'offset':str(day), 'directory':dir_month})
                os.system('zip -r ' + dir_month + '.zip ' + dir_month)
        #~~~~~~~~~~~main~end~~~~~~~~~~ 
        time.sleep(600)


if __name__ == '__main__':
    run_main()
